package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FoodadditiveRestController")
public class FoodadditiveRestController extends CmiEmaController {

	/**
	 * Create a new Foodadditive entity
	 * 
	 */
	@RequestMapping(value = "/newFoodadditive", method = RequestMethod.POST)
	@ResponseBody
	public Object newFoodadditive(@RequestBody Foodadditive foodadditive) {
		foodadditiveService.saveFoodadditive(foodadditive);
		return JSONObject
				.parse(cmiPsonService.toJsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditive.getId()), 2));
	}

	@RequestMapping(value = "/restNewFoodadditive", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFoodadditive(@RequestBody String foodadditiveJson) {
		Foodadditive foodadditive = new Gson().fromJson(foodadditiveJson, Foodadditive.class);
		appendReferences(foodadditive);
		foodadditiveService.saveFoodadditive(foodadditive);
		return JSONObject
				.parse(cmiPsonService.toJsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditive.getId()), 2));
	}

	@RequestMapping(value = "/saveFoodadditive", method = RequestMethod.PUT)
	@ResponseBody
	public Foodadditive saveFoodadditive(@RequestBody Foodadditive foodadditive) {
		foodadditiveService.saveFoodadditive(foodadditive);
		return foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditive.getId());
	}

	@RequestMapping(value = "/restSaveFoodadditive", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFoodadditive(@RequestBody String foodadditiveJson) {
		Foodadditive foodadditive = new Gson().fromJson(foodadditiveJson, Foodadditive.class);
		appendReferences(foodadditive);
		CmiPsonService cmiPsonService = new CmiPsonService();
		foodadditiveService.saveFoodadditive(foodadditive);
		return JSONObject
				.parse(cmiPsonService.toJsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditive.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFoodadditive/{foodadditiveId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFoodadditive(@PathVariable Integer foodadditiveId) {
		Foodadditive foodadditive = foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditiveId);
		foodadditiveService.deleteFoodadditive(foodadditive);
	}

	@RequestMapping(value = "/restConfirmDeleteFoodadditives")
	@ResponseBody
	public Object restConfirmDeleteFoodadditives(@RequestBody Set<Integer> deleteFoodadditivesIds) {
		Set<Foodadditive> deleteFoodadditives = foodadditiveDAO.findFoodadditivesByIds(deleteFoodadditivesIds);
		Set<Foodadditive> referencedFoodadditives = foodadditiveService.loadReferenceFoodadditives(deleteFoodadditives);
		deleteFoodadditives.removeAll(referencedFoodadditives);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFoodadditives);
		jsonObject.put("deleteEntitys", deleteFoodadditives);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFoodadditives")
	@ResponseBody
	public Object restDeleteFoodadditives(@RequestBody Set<Foodadditive> deleteFoodadditives) {
		Iterator<Foodadditive> iterator = deleteFoodadditives.iterator();
		while (iterator.hasNext()) {
			Foodadditive currentFoodadditive = iterator.next();
			foodadditiveService.deleteFoodadditive(currentFoodadditive);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFoodadditives");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFoodadditive/{foodadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodadditive(@PathVariable Integer foodadditiveId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditiveId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodadditiveAdditive/{foodadditiveId}/additive", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodadditiveAdditive(@PathVariable Integer foodadditiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditiveId).getAdditive(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFoodadditiveFood/{foodadditiveId}/food", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFoodadditiveFood(@PathVariable Integer foodadditiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditiveId).getFood(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Foodadditive foodadditive) {

		Additive additive = foodadditive.getAdditive();
		if (additive != null)
			foodadditive.setAdditive(additiveService.findAdditiveByPrimaryKey(additive.getId()));

		Food food = foodadditive.getFood();
		if (food != null)
			foodadditive.setFood(foodService.findFoodByPrimaryKey(food.getId()));

	}

	@RequestMapping(value = "/restGetFoodadditiveAdditive/{foodadditiveId}/additive", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodadditiveAdditive(@PathVariable Integer foodadditiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditiveId).getAdditive(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFoodadditiveFood/{foodadditiveId}/food", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFoodadditiveFood(@PathVariable Integer foodadditiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(foodadditiveDAO.findFoodadditiveByPrimaryKey(foodadditiveId).getFood(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFoodadditives", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFoodadditives() {
		return JSONObject.parse(cmiPsonService.toJsonString(foodadditiveService.loadFoodadditives(), 2));
	}

	@RequestMapping(value = "/restListFoodadditivesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFoodadditivesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = foodadditivePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Foodadditive> foodadditives = foodadditiveDAO.findAllFoodadditives(startResult,
				cmiPagination.getPaginationSize());
		String foodadditiveString = cmiPsonService.toPsonString(foodadditives, 2, cmiPagination);

		return JSONObject.parse(foodadditiveString);
	}

	@RequestMapping("/foodadditiveSelectBox")
	@ResponseBody
	public JSONObject foodadditiveSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Additive":
				entitySet = additiveService.loadAdditivesByIdSet(searchValue);
				break;
			case "Food":
				entitySet = foodService.loadFoodsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Additive":
				entitySet = additiveDAO.findAllAdditives((pageNumber - 1) * paginationSize, paginationSize);
				count = additiveService.countAdditives();
				break;
			case "Food":
				entitySet = foodDAO.findAllFoods((pageNumber - 1) * paginationSize, paginationSize);
				count = foodService.countFoods();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Additive":
				entitySet = additiveDAO.findAdditiveByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = additiveService.countAdditivesByName(queryword);
				break;
			case "Food":
				entitySet = foodDAO.findFoodByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodService.countFoodsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
